#!usr/bin/env python  
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: tap_connector28_kingbase.py 
@version:
@time: 2022/09/06 
"""
from TapClientConnector.connector import TAPOracleConnector
from jpype import dbapi2
from TapClientConnector.connector.tap_connector00_base import *

"""
com.kingbase8.Driver
jdbc_str: "jdbc:kingbase8://localhost:54321/testdb?user=system&password=manager";
"""


class TAPKingBaseR3Connector(TAPOracleConnector):

    def __init__(self, kwargs):
        super(TAPOracleConnector, self).__init__(kwargs)
        host = self.FORMAT_DB_INFO.get('host')
        port = self.FORMAT_DB_INFO.get('port')
        user = self.FORMAT_DB_INFO.get('user')
        password = self.FORMAT_DB_INFO.get('password')
        database = self.FORMAT_DB_INFO.get('database')
        self.connector = dbapi2.connect(
            dsn=f'jdbc:kingbase8://{host}:{port}/{database}',
            driver='com.kingbase8.Driver',
            driver_args={'user': user, 'password': password, }
        )

    @connector_query_logger
    def show_tables(self) -> list:
        table_list = []
        for i in self._query(f"select table_name from user_tables"):
            table_list.append(i[0])
        return table_list

    @connector_query_logger
    def show_dbs(self) -> list:
        db_list = []
        for i in self._query('select datname from sys_database'):
            db_list.append(i[0])
        return db_list

    def _query(self, sql):
        cursor = self.connector.cursor()
        try:
            cursor.execute(sql)
        except Exception:
            raise SQLError
        res = list(cursor.fetchall())
        # tuple 处理与其他关系数据库一致
        res = [tuple(i) for i in res]
        self.TABLE_DESCRIPTION = [one[0] for one in cursor.description]
        cursor.close()
        return res
if __name__ == '__main__':
    from TapDataSourceInfo.db_info_pdk import KingBaseR3

    T = TAPKingBaseR3Connector(KingBaseR3.AUTO_KingBaseR3_SOURCE)
    print(T.show_dbs())
    print(T.show_tables())
    # T.exec('create table "PUBLIC"."test" (pk int)')
    # T.exec('insert into "PUBLIC"."test" values(1)')
    print(T.query('select * from "PUBLIC"."test"'))
    # T.exec('delete from "SOURCE".Jarad_All_Type')
